package com.llh.formmode;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import weaver.conn.RecordSet;
import weaver.formmode.webservices.ModeDataServiceImpl;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname FormmodeUtil
 * @Description 表单建模工具类
 * @Version 1.0.0
 * @Date 2022/8/25 0025 14:11
 * @Created by 刘立华
 */
public class FormmodeUtil {

    private String modeid;
    private String orderid;
    private Map<String, String> modeinfo;
    private Logger log = LoggerFactory.getLogger(FormmodeUtil.class);

    public FormmodeUtil(String modeid, String orderid) {
        this.modeid = modeid;
        this.orderid = orderid;
        this.modeinfo = getModeInfo();
        log.info("modeid = " + modeid);
        log.info("modeinfo = " + modeinfo);
    }

    public Map<String, String> getModeInfo() {
        Map<String, String> map = new HashMap<String, String>();
        RecordSet rs = new RecordSet();
        String sql = "select a.formid,b.id,b.tablename from  Modeinfo a ,workflow_bill b where a.formid =b.id and a.id=?";
        rs.executeQuery(sql, modeid);
        if (rs.next()) {
            map.put("formid", Util.null2String(rs.getString("formid")));
            map.put("billid", Util.null2String(rs.getString("id")));
            map.put("tablename", Util.null2String(rs.getString("tablename")));
        }
        return map;
    }

    public List<Map<String, String>> getMainTableFields() {
        int billid = Util.getIntValue((String) modeinfo.get("billid"), 0);
        if (billid != 0) {
            return getMainTableFields(billid);
        }
        return null;
    }

    public List<Map<String, String>> getDetailTableFields() {
        int billid = Util.getIntValue((String) modeinfo.get("billid"), 0);
        if (billid != 0) {
            return getDetailTableFields(billid, Util.getIntValue(orderid, 0));
        }
        return null;
    }


    /**
     * 根据单据id查询主表的字段信息：数据库字段名称、字段类型、字段描述
     *
     * @param billid 单据id
     * @return List<Map < String, Object>>
     */
    public List<Map<String, String>> getMainTableFields(int billid) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        RecordSet rs = new RecordSet();
        String sql = "select  a.fieldname,b.labelname filedlabel ,a.fielddbtype from workflow_billfield a,HtmlLabelInfo b where a.fieldlabel =b.indexid and b.languageid =7 and a.billid =? and a.viewtype = 0";
        rs.executeQuery(sql, billid);
        while (rs.next()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("fieldname", Util.null2String(rs.getString("fieldname")));
            map.put("filedlabel", Util.null2String(rs.getString("filedlabel")));
            map.put("fielddbtype", Util.null2String(rs.getString("fielddbtype")));
            list.add(map);
        }
        return list;
    }

    /**
     * 根据单据id，orderid 查询对应建模明细的字段信息：数据库字段名称、字段类型、字段描述
     *
     * @param billid
     * @param orderid
     * @return
     */
    public List<Map<String, String>> getDetailTableFields(int billid, int orderid) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        RecordSet rs = new RecordSet();
        String sql = "select a.fieldname, b.labelname filedlabel , a.fielddbtype,a.detailtable from workflow_billfield a, HtmlLabelInfo b where a.fieldlabel = b.indexid and b.languageid = 7 and a.billid =? and a.viewtype = 1 and a.detailtable = (select tablename from workflow_billdetailtable where billid =? and orderid=?) ";
        rs.executeQuery(sql, billid, billid, orderid);
        while (rs.next()) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("fieldname", Util.null2String(rs.getString("fieldname")));
            map.put("filedlabel", Util.null2String(rs.getString("filedlabel")));
            map.put("fielddbtype", Util.null2String(rs.getString("fielddbtype")));
            map.put("detailtable", Util.null2String(rs.getString("detailtable")));
            list.add(map);
        }
        return list;
    }

    public String getServiceXml(String mainid, StringBuilder mainXml, StringBuilder detailXml) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        sb.append("<ROOT>");
        sb.append("<header>");
        sb.append("<userid>1</userid>");
        sb.append("<modeid>" + modeid + "</modeid>");
        sb.append("<doPageexpandInterface>Y</doPageexpandInterface>");
        sb.append("<id>" + mainid + "</id>");
        sb.append("</header>");
        sb.append("<search>");
        sb.append("<condition />");
        sb.append("<right>Y</right>");//是否验证权限
        sb.append("</search>");
        sb.append("<data id=\"\">");
        sb.append("<maintable>");
        sb.append(mainXml.toString());
        sb.append("</maintable>");
        sb.append("<detail>");
        sb.append("</detail>");
        sb.append(detailXml.toString());
        sb.append("</data>");
        sb.append("</ROOT>");
        return sb.toString();
    }

    /**
     * 建模主表明细写入数据
     *
     * @param mainData   主表json数据
     * @param detailData 明细json数据
     * @param mainid     主表数据id
     * @return @param id 插入或修改的主表id
     */
    public String addOrModify(JSONObject mainData, JSONArray detailData, String mainid) {
        if (mainData == null) {
            return "";
        }
        List<Map<String, String>> mainTableFields = getMainTableFields();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mainTableFields.size(); i++) {
            Map<String, String> map = mainTableFields.get(i);
            String filedvalue = mainData.getStr(map.get("fieldname"));
            map.put("filedvalue", filedvalue);
            sb.append("<field>");
            sb.append("<filedname>" + map.get("fieldname") + "</filedname>");//数据库名称
            sb.append("<filedlabel>" + map.get("filedlabel") + "</filedlabel>");//字段名称
            sb.append("<fileddbtype>" + map.get("fielddbtype") + "</fileddbtype>");//数据库类型
            sb.append("<filedvalue>" + map.get("filedvalue") + "</filedvalue>");//字段的值
            sb.append("<fieldshowname>" + map.get("fieldshowname") + "</fieldshowname>");
            sb.append("</field>");
        }
        log.info("mainTableFields = " + mainTableFields);
        //  log.info("mainTableFieldsXml = " + sb.toString());
        StringBuilder sbdt = new StringBuilder();
        int detailindex = Util.getIntValue(orderid, 0);
        if (detailindex > 0 && detailData != null) {
            //id为明细表序号  第一个从0开始
            List<Map<String, String>> detailTableFields = getDetailTableFields();
            if (detailTableFields.size() > 0) {
                sbdt.append("<detailtable id='" + detailindex + "'>");
                for (int i = 0; i < detailData.size(); i++) {
                    int hh = i + 1;
                    JSONObject jsonObject = (JSONObject) detailData.get(i);
                    sbdt.append("<row id='" + hh + "' action='add'>");
                    for (int j = 0; j < detailTableFields.size(); j++) {
                        Map<String, String> map = detailTableFields.get(j);
                        String filedvalue = jsonObject.getStr(map.get("fieldname"));
                        map.put("filedvalue", filedvalue);
                        sbdt.append("<field>");
                        sbdt.append("<filedname>" + map.get("fieldname") + "</filedname>");//数据库名称
                        sbdt.append("<filedlabel>" + map.get("filedlabel") + "</filedlabel>");//字段名称
                        sbdt.append("<fileddbtype>" + map.get("fielddbtype") + "</fileddbtype>");//数据库类型
                        sbdt.append("<filedvalue>" + map.get("filedvalue") + "</filedvalue>");//字段的值
                        sbdt.append("<fieldshowname>" + map.get("fieldshowname") + "</fieldshowname>");
                        sbdt.append("</field>");
                    }
                    sbdt.append("</row>");
                }
                sbdt.append("</detailtable>");
            }
            log.info("detailTableFields = " + detailTableFields);
        }
        // log.info("detailTableXml = " + sbdt.toString());
        String serviceXml = getServiceXml(mainid, sb, sbdt);
        log.info("serviceXml = " + XmlUtil.format(serviceXml));
        ModeDataServiceImpl client = new ModeDataServiceImpl();
        //{"ROOT":{"return":{"returnnode":0,"returnmessage":"操作成功!","id":11}}}
        String s = String.valueOf(JSONUtil.parseFromXml(client.saveModeData(serviceXml)));
        log.info("执行结果" + s);
        String id = "";
        if (JSONUtil.isJsonObj(s)) {
            JSONObject parseObj = JSONUtil.parseObj(s);
            JSONObject returnObj = parseObj.getJSONObject("ROOT").getJSONObject("return");
            String returnnode = returnObj.getStr("returnnode");
            String returnmessage = returnObj.getStr("returnmessage");
            if ("0".equals(returnnode)) {
                id = returnObj.getStr("id");
            }
        }
        return id;
    }
}